from django.core.management.base import BaseCommand
from faker import Faker
from blog.models import *
from django.contrib.auth import get_user_model
import random

class Command(BaseCommand):
    help = '生成文章数据'

    def handle(self, *args, **options):
        fake = Faker('zh_CN')
        User = get_user_model()
        all_authors = User.objects.all()
        all_categories = Category.objects.all()
        all_tags = Tag.objects.all()

        if not all_authors:
            self.stdout.write('没有找到任何用户，请先创建用户')
            return
        
        for _ in range(10):
            article = Article.objects.create(
                title=fake.sentence(nb_words=5),
                content=fake.text(),
                author=random.choice(all_authors),
                category=random.choice(all_categories) if all_categories else None,
            )
            
            if all_tags:
                selected_tags = random.sample(list(all_tags), random.randint(1, 3))
                article.tags.set(selected_tags)
            
        self.stdout.write('生成完成')

